#include "../include/sidebarwidget.h"
#include "../include/config.h"
#include <QApplication>
#include <QPixmap>
#include <QPainter>
#include <QBrush>
#include <QFile>
#include <QIODevice>

SidebarWidget::SidebarWidget(AuthService *authService, QWidget *parent)
    : QWidget(parent)
    , m_authService(authService)
    , m_collapsed(false)
    , m_expandedWidth(Config::getSidebarExpandedWidth())
    , m_collapsedWidth(Config::getSidebarCollapsedWidth())
    , m_currentTheme("dark")
    , m_primaryColor(Config::getPrimaryColor())
    , m_secondaryColor(Config::getSecondaryColor())
    , m_backgroundColor(Config::getBackgroundColor())
    , m_textColor(Config::getTextColor())
    , m_hoverColor(Config::getHoverColor())
    , m_activeColor("#3498DB")
    , m_isInGame(false)
{
    setupUI();
    applyStyles();

    // 初始化所有按钮的属性
    initializeButtonProperties();

    // 设置初始宽度和大小策略
    setMinimumWidth(m_expandedWidth);  // 初始为展开状态
    setMaximumWidth(m_expandedWidth);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);

    // 设置动画 - 优化动画效果
    m_collapseAnimation = new QPropertyAnimation(this, "maximumWidth", this);
    m_collapseAnimation->setDuration(250);  // 稍微加快动画速度
    m_collapseAnimation->setEasingCurve(QEasingCurve::OutCubic);  // 更自然的缓动效果
}

SidebarWidget::~SidebarWidget()
{
    // 停止动画
    if (m_collapseAnimation) {
        m_collapseAnimation->stop();
    }
    // QPropertyAnimation和其他UI组件通过Qt的父子关系自动管理
}

void SidebarWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);

    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setObjectName("sidebarScrollArea");

    m_contentWidget = new QWidget();
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(0, 0, 0, 0);
    m_contentLayout->setSpacing(0);

    setupUserProfile();
    addSeparator();
    setupNavigationMenu();

    // 在统一菜单和底部按钮之间添加空白
    m_contentLayout->addStretch();

    setupFooter();

    m_scrollArea->setWidget(m_contentWidget);
    m_mainLayout->addWidget(m_scrollArea);
}

void SidebarWidget::setupUserProfile()
{
    m_userProfileWidget = new QWidget();
    m_userProfileWidget->setObjectName("userProfileWidget");
    m_userProfileWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_userProfileWidget->setMinimumHeight(70); // 增加最小高度，确保有足够空间显示用户信息

    m_userProfileLayout = new QHBoxLayout(m_userProfileWidget);
    m_userProfileLayout->setContentsMargins(10, 10, 10, 10); // 与CSS padding保持一致
    m_userProfileLayout->setSpacing(12); // 增加间距，更清晰

    // 头像容器
    m_avatarContainer = new QWidget();
    m_avatarContainer->setObjectName("avatarContainer");
    m_avatarContainer->setFixedSize(65, 65);
    QVBoxLayout *avatarLayout = new QVBoxLayout(m_avatarContainer);
    avatarLayout->setContentsMargins(0, 0, 0, 0);
    avatarLayout->setAlignment(Qt::AlignCenter);

    m_avatarLabel = new QLabel();
    m_avatarLabel->setObjectName("avatarLabel");
    m_avatarLabel->setFixedSize(65, 65);
    m_avatarLabel->setScaledContents(true);
    m_avatarLabel->setAlignment(Qt::AlignCenter);
    avatarLayout->addWidget(m_avatarLabel);
    
    // 创建默认头像
    QPixmap avatar(65, 65);
    avatar.fill(Qt::transparent);
    QPainter painter(&avatar);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(QColor(m_primaryColor)));
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(0, 0, 60, 60);
    painter.setPen(QColor("#FFFFFF"));
    painter.setFont(QFont("Arial", 18, QFont::Bold));
    painter.drawText(avatar.rect(), Qt::AlignCenter, "U");
    m_avatarLabel->setPixmap(avatar);

    m_userProfileLayout->addWidget(m_avatarContainer);

    // 用户信息容器
    m_userInfoWidget = new QWidget();
    m_userInfoWidget->setObjectName("userInfoWidget");
    m_userInfoWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_userInfoWidget->setMinimumHeight(70); // 增加最小高度，确保状态和等级有足够空间
    m_userInfoLayout = new QVBoxLayout(m_userInfoWidget);
    m_userInfoLayout->setContentsMargins(4, 8, 4, 8); // 增加垂直边距，减少水平边距
    m_userInfoLayout->setSpacing(6); // 增加间距，更清晰

    m_usernameLabel = new QLabel("游客");
    m_usernameLabel->setObjectName("usernameLabel");
    m_usernameLabel->setWordWrap(true);
    m_usernameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 状态和等级容器
    QWidget *statusContainer = new QWidget();
    QHBoxLayout *statusLayout = new QHBoxLayout(statusContainer);
    statusLayout->setContentsMargins(0, 0, 0, 0);
    statusLayout->setSpacing(6); // 减少间距，使状态和等级更紧凑

    m_statusLabel = new QLabel("🔴 离线");
    m_statusLabel->setObjectName("statusLabel");

    m_levelLabel = new QLabel("⭐ Lv.1");
    m_levelLabel->setObjectName("levelLabel");

    statusLayout->addWidget(m_statusLabel);
    statusLayout->addWidget(m_levelLabel); // 去除拉伸空白，紧凑排列

    m_userInfoLayout->addWidget(m_usernameLabel);
    m_userInfoLayout->addWidget(statusContainer);
    // 去除拉伸空白

    m_userProfileLayout->addWidget(m_userInfoWidget); // 去除比例，使用固定大小
    m_contentLayout->addWidget(m_userProfileWidget);
}

void SidebarWidget::setupNavigationMenu()
{
    // 统一的菜单组 - 去除标题
    m_navigationGroup = new QWidget();
    m_navigationGroup->setObjectName("sidebarGroup");
    m_navigationGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_navigationLayout = new QVBoxLayout(m_navigationGroup);
    m_navigationLayout->setContentsMargins(8, 8, 8, 8); // 增加边距，更美观
    m_navigationLayout->setSpacing(6); // 增加按钮间距，更清晰

    // 游戏功能按钮
    m_gameServersButton = createMenuButton("🎮 游戏服务", "gameServers", "浏览和加入游戏服务器");
    m_gameServersButton->setProperty("menuType", "primary");
    connect(m_gameServersButton, &QPushButton::clicked, this, &SidebarWidget::gameServersClicked);
    connect(m_gameServersButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_gameServersButton);

    m_friendsButton = createMenuButton("👥 好友列表", "friends", "查看在线好友和聊天");
    connect(m_friendsButton, &QPushButton::clicked, this, &SidebarWidget::friendsClicked);
    connect(m_friendsButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_friendsButton);

    m_statisticsButton = createMenuButton("📊 游戏统计", "statistics", "查看详细游戏数据");
    connect(m_statisticsButton, &QPushButton::clicked, this, &SidebarWidget::statisticsClicked);
    connect(m_statisticsButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_statisticsButton);

    // 添加分隔线
    addMenuSeparator(m_navigationLayout);

    // 个人功能按钮
    m_profileButton = createMenuButton("👤 个人中心", "profile", "编辑个人资料和偏好设置");
    connect(m_profileButton, &QPushButton::clicked, this, &SidebarWidget::profileClicked);
    connect(m_profileButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_profileButton);

    m_settingsButton = createMenuButton("⚙️ 应用设置", "settings", "配置应用程序选项");
    connect(m_settingsButton, &QPushButton::clicked, this, &SidebarWidget::settingsClicked);
    connect(m_settingsButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_settingsButton);

    m_helpButton = createMenuButton("❓ 帮助支持", "help", "获取使用帮助和技术支持");
    connect(m_helpButton, &QPushButton::clicked, this, &SidebarWidget::helpClicked);
    connect(m_helpButton, &QPushButton::clicked, this, &SidebarWidget::onMenuItemClicked);
    m_navigationLayout->addWidget(m_helpButton);

    m_contentLayout->addWidget(m_navigationGroup);
}

void SidebarWidget::setupQuickActions()
{
    // 此方法现在为空，所有按钮已合并到setupNavigationMenu中
}

void SidebarWidget::setupFooter()
{
    m_footerWidget = new QWidget();
    m_footerWidget->setObjectName("footerWidget");
    m_footerWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_footerLayout = new QVBoxLayout(m_footerWidget);
    m_footerLayout->setContentsMargins(8, 8, 8, 8); // 增加边距，更美观
    m_footerLayout->setSpacing(6); // 增加间距，更清晰

    // 退出登录按钮
    m_logoutButton = createMenuButton("🚪 安全退出", "logout", "退出登录并关闭应用");
    m_logoutButton->setObjectName("logoutButton");
    connect(m_logoutButton, &QPushButton::clicked, this, &SidebarWidget::logoutClicked);
    m_footerLayout->addWidget(m_logoutButton);

    // 添加分隔线
    addMenuSeparator(m_footerLayout);

    // 折叠按钮
    m_collapseButton = createMenuButton("◀ 收起", "collapse", "收起/展开侧边栏");
    m_collapseButton->setObjectName("collapseButton");
    m_collapseButton->setFixedHeight(35);
    connect(m_collapseButton, &QPushButton::clicked, this, &SidebarWidget::onToggleCollapse);
    m_footerLayout->addWidget(m_collapseButton);

    m_contentLayout->addWidget(m_footerWidget);
}

QPushButton* SidebarWidget::createMenuButton(const QString &text, const QString &icon, const QString &tooltip)
{
    QPushButton *button = new QPushButton(text);
    button->setObjectName("menuButton");
    button->setToolTip(tooltip);
    button->setFixedHeight(45);
    button->setCursor(Qt::PointingHandCursor);
    button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 设置按钮属性用于样式
    button->setProperty("menuType", icon);
    button->setProperty("active", false);

    return button;
}

void SidebarWidget::addMenuSeparator(QVBoxLayout *layout)
{
    QFrame *separator = new QFrame();
    separator->setObjectName("menuSeparator");
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Sunken);
    separator->setFixedHeight(1);
    separator->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    layout->addWidget(separator);
}

void SidebarWidget::addSeparator()
{
    QFrame *separator = new QFrame();
    separator->setObjectName("separator");
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Plain);  // 使用Plain样式，让CSS控制外观
    separator->setFixedHeight(1);
    separator->setProperty("collapsed", m_collapsed);  // 设置折叠状态属性
    m_contentLayout->addWidget(separator);
}

void SidebarWidget::updateUserInfo(const AuthService::UserInfo &userInfo)
{
    // 确保标签可见
    m_usernameLabel->setVisible(true);
    m_statusLabel->setVisible(true);
    m_levelLabel->setVisible(true);

    // 设置文本内容
    m_usernameLabel->setText(userInfo.username);
    m_statusLabel->setText("🟢 在线");

    int level = userInfo.loginCount / 10 + 1;
    m_levelLabel->setText(QString("⭐ Lv.%1").arg(level));

    // 强制重绘标签
    m_usernameLabel->update();
    m_statusLabel->update();
    m_levelLabel->update();

    // 更新头像首字母
    if (!userInfo.username.isEmpty()) {
        QPixmap avatar(60, 60);
        avatar.fill(Qt::transparent);
        QPainter painter(&avatar);
        painter.setRenderHint(QPainter::Antialiasing);

        // 绘制渐变背景
        QRadialGradient gradient(30, 30, 30);
        gradient.setColorAt(0, QColor(m_primaryColor));
        gradient.setColorAt(1, QColor("#3498DB"));
        painter.setBrush(QBrush(gradient));
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(0, 0, 60, 60);

        // 绘制文字
        painter.setPen(QColor("#FFFFFF"));
        painter.setFont(QFont("Arial", 18, QFont::Bold));
        painter.drawText(avatar.rect(), Qt::AlignCenter, userInfo.username.left(1).toUpper());

        // 添加边框
        painter.setPen(QPen(QColor("#FFFFFF"), 2));
        painter.setBrush(Qt::NoBrush);
        painter.drawEllipse(1, 1, 58, 58);

        m_avatarLabel->setPixmap(avatar);
    }
}

void SidebarWidget::setCollapsed(bool collapsed)
{
    if (m_collapsed == collapsed) return;
    
    m_collapsed = collapsed;
    updateCollapseState();
}

void SidebarWidget::onToggleCollapse()
{
    setCollapsed(!m_collapsed);
}

void SidebarWidget::updateCollapseState()
{
    int targetWidth = m_collapsed ? m_collapsedWidth : m_expandedWidth;

    // 同时更新最小宽度和最大宽度以确保动画效果
    setMinimumWidth(targetWidth);
    m_collapseAnimation->setStartValue(maximumWidth());
    m_collapseAnimation->setEndValue(targetWidth);

    // 连接动画完成信号，确保在动画完成后进行布局调整
    connect(m_collapseAnimation, &QPropertyAnimation::finished, this, [this]() {
        // 断开之前的连接，避免重复连接
        disconnect(m_collapseAnimation, &QPropertyAnimation::finished, this, nullptr);

        // 在动画完成后进行最终的布局调整
        if (!m_collapsed) {
            // 展开完成后，确保用户信息正确显示
            forceUpdateUserInfo();
        }

        // 强制重新应用样式，确保CSS生效
        style()->unpolish(this);
        style()->polish(this);

        // 强制重新布局
        updateGeometry();
        if (parentWidget()) {
            parentWidget()->updateGeometry();
        }
    });

    m_collapseAnimation->start();

    // 设置所有容器的折叠状态属性
    m_userProfileWidget->setProperty("collapsed", m_collapsed);
    m_avatarContainer->setProperty("collapsed", m_collapsed);
    m_userInfoWidget->setProperty("collapsed", m_collapsed);
    m_navigationGroup->setProperty("collapsed", m_collapsed);

    // 立即调整用户资料区域显示
    if (m_collapsed) {
        // 收起状态：只显示小头像，隐藏用户信息
        m_userInfoWidget->setVisible(false);
        updateAvatarSize(40);  // 稍微增大收缩状态的头像
        // 调整头像容器大小适应收起状态
        m_avatarContainer->setFixedSize(40, 40);
        // 调整用户资料布局为居中对齐
        m_userProfileLayout->setAlignment(Qt::AlignCenter);
        m_userProfileLayout->setContentsMargins(10, 10, 10, 10); // 适应60px宽度，更均匀的边距
        // 不设置固定高度，让CSS控制
    } else {
        // 展开状态：显示完整用户信息和大头像
        // 首先恢复布局设置
        m_userProfileLayout->setAlignment(Qt::AlignLeft);
        m_userProfileLayout->setContentsMargins(10, 10, 10, 10);  // 与CSS padding保持一致

        // 恢复容器大小
        m_avatarContainer->setFixedSize(60, 60);
        // 不设置固定高度，让CSS控制
        m_userProfileWidget->setMinimumHeight(90); // 只设置最小高度，与CSS一致

        // 确保用户资料容器可见
        m_userProfileWidget->setVisible(true);
        m_userProfileWidget->show();

        // 显示用户信息容器
        m_userInfoWidget->setVisible(true);
        m_userInfoWidget->show();

        // 更新头像大小
        updateAvatarSize(60);

        // 强制重新布局
        m_userProfileWidget->updateGeometry();
        m_userInfoWidget->updateGeometry();

        // 立即重新设置用户信息内容
        if (m_authService && m_authService->isAuthenticated()) {
            AuthService::UserInfo userInfo = m_authService->getCurrentUser();
            // 重新设置用户名
            m_usernameLabel->setText(userInfo.username);
            m_usernameLabel->setVisible(true);
            // 重新设置状态
            m_statusLabel->setText("🟢 在线");
            m_statusLabel->setVisible(true);
            // 重新设置等级
            int level = userInfo.loginCount / 10 + 1;
            m_levelLabel->setText(QString("⭐ Lv.%1").arg(level));
            m_levelLabel->setVisible(true);

            // 强制重绘标签
            m_usernameLabel->update();
            m_statusLabel->update();
            m_levelLabel->update();
        }
    }

    // 强制重新应用样式
    m_userProfileWidget->style()->unpolish(m_userProfileWidget);
    m_userProfileWidget->style()->polish(m_userProfileWidget);
    m_avatarContainer->style()->unpolish(m_avatarContainer);
    m_avatarContainer->style()->polish(m_avatarContainer);
    m_navigationGroup->style()->unpolish(m_navigationGroup);
    m_navigationGroup->style()->polish(m_navigationGroup);

    // 统一菜单组不需要标题，因为已经去除了QGroupBox

    // 更新按钮文本显示和状态属性
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    for (QPushButton *btn : buttons) {
        // 设置折叠状态属性，让CSS处理样式
        btn->setProperty("collapsed", m_collapsed);

        // 处理导航按钮
        if (btn->objectName() == "menuButton") {
            QString fullText = btn->property("fullText").toString();
            if (fullText.isEmpty()) {
                btn->setProperty("fullText", btn->text());
                fullText = btn->text();
            }

            if (m_collapsed) {
                // 只显示图标部分
                QString icon = fullText.split(" ").first();
                btn->setText(icon);
            } else {
                btn->setText(fullText);
            }
        }
        // 处理底部按钮
        else if (btn->objectName() == "logoutButton") {
            QString fullText = btn->property("fullText").toString();
            if (fullText.isEmpty()) {
                btn->setProperty("fullText", btn->text());
                fullText = btn->text();
            }

            if (m_collapsed) {
                // 只显示图标
                QString icon = fullText.split(" ").first();
                btn->setText(icon);
            } else {
                btn->setText(fullText);
            }
        }
        else if (btn->objectName() == "collapseButton") {
            // 折叠按钮特殊处理，始终显示对应的图标
            if (m_collapsed) {
                btn->setText("▶");
                btn->setToolTip("展开侧边栏");
            } else {
                btn->setText("◀ 收起");
                btn->setToolTip("收起侧边栏");
            }
        }

        // 强制重新应用样式
        btn->style()->unpolish(btn);
        btn->style()->polish(btn);
    }
}

void SidebarWidget::onMenuItemClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;
    
    // 重置所有按钮状态
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    for (QPushButton *btn : buttons) {
        if (btn->objectName() == "menuButton") {
            btn->setProperty("active", false);
            btn->style()->unpolish(btn);
            btn->style()->polish(btn);
        }
    }
    
    // 设置当前按钮为活动状态
    button->setProperty("active", true);
    button->style()->unpolish(button);
    button->style()->polish(button);
}

void SidebarWidget::setTheme(const QString &theme)
{
    m_currentTheme = theme;

    // 更新颜色配置
    if (theme == "dark") {
        m_primaryColor = "#4A90E2";
        m_backgroundColor = "#2C3E50";
        m_textColor = "#ECF0F1";
        m_hoverColor = "#34495E";
    } else if (theme == "light") {
        m_primaryColor = "#3498DB";
        m_backgroundColor = "#ECF0F1";
        m_textColor = "#2C3E50";
        m_hoverColor = "#BDC3C7";
    }

    // 重新应用样式
    applyStyles();

    // 更新用户头像
    if (m_authService && m_authService->isAuthenticated()) {
        updateUserInfo(m_authService->getCurrentUser());
    }
}

void SidebarWidget::applyStyles()
{
    // 加载专门的侧边栏样式文件
    QFile styleFile(":/styles/sidebar.qss");
    if (styleFile.open(QIODevice::ReadOnly)) {
        QString styleSheet = QString::fromUtf8(styleFile.readAll());
        setStyleSheet(styleSheet);
        styleFile.close();
        return;
    }

    // 如果样式文件加载失败，使用备用样式
    QString gradientColors;
    QString borderColor;
    QString groupBackground;
    QString buttonBackground;
    QString profileBackground;
    QString primaryAccent;
    QString secondaryAccent;
    QString hoverAccent;
    QString activeAccent;

    if (m_currentTheme == "dark") {
        // 深色主题 - 统一的颜色系统
        gradientColors = "stop:0 #2C3E50, stop:0.5 #34495E, stop:1 #2C3E50";
        borderColor = "rgba(74, 144, 226, 0.5)";
        groupBackground = "rgba(52, 73, 94, 0.95)";
        buttonBackground = "rgba(44, 62, 80, 0.7)";
        profileBackground = "rgba(74, 144, 226, 0.2)";
        primaryAccent = "#4A90E2";
        secondaryAccent = "#3498DB";
        hoverAccent = "rgba(74, 144, 226, 0.8)";
        activeAccent = "rgba(52, 152, 219, 0.9)";
    } else {
        // 浅色主题 - 统一的颜色系统
        gradientColors = "stop:0 #ECF0F1, stop:0.5 #D5DBDB, stop:1 #ECF0F1";
        borderColor = "rgba(52, 152, 219, 0.5)";
        groupBackground = "rgba(255, 255, 255, 0.95)";
        buttonBackground = "rgba(236, 240, 241, 0.7)";
        profileBackground = "rgba(52, 152, 219, 0.2)";
        primaryAccent = "#3498DB";
        secondaryAccent = "#2980B9";
        hoverAccent = "rgba(52, 152, 219, 0.8)";
        activeAccent = "rgba(41, 128, 185, 0.9)";
    }

    setStyleSheet(QString(R"(
        SidebarWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                %1);
            border-right: 3px solid %2;
        }

        #sidebarScrollArea {
            background: transparent;
            border: none;
        }

        /* 确保所有子组件都有正确的背景 */
        #sidebarScrollArea QWidget {
            background-color: transparent;
        }

        #sidebarScrollArea QScrollBar:vertical {
            background-color: rgba(52, 73, 94, 0.3);
            width: 8px;
            border-radius: 4px;
        }

        #sidebarScrollArea QScrollBar::handle:vertical {
            background-color: %2;
            border-radius: 4px;
            min-height: 20px;
        }

        #sidebarScrollArea QScrollBar::handle:vertical:hover {
            background-color: #5DADE2;
        }

        #userProfileWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %5, stop:0.3 rgba(74, 144, 226, 0.25), stop:1 rgba(52, 152, 219, 0.1));
            border: 2px solid %2;
            border-radius: 16px;
            margin: 6px 1px; /* 适应80px宽度 */
            padding: 4px; /* 适中的内边距 */
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); /* 添加轻微阴影 */
            min-height: 70px; /* 确保最小高度 */
        }

        /* 收起状态的用户资料样式 */
        #userProfileWidget[collapsed="true"] {
            margin: 6px 2px; /* 收起时稍微增加边距 */
            padding: 8px 2px; /* 收起时调整内边距 */
            min-height: 45px; /* 收起时的最小高度 */
            max-height: 45px; /* 收起时的最大高度 */
        }

        #avatarLabel {
            border: none; /* 移除CSS边框，改为在代码中动态控制 */
            border-radius: 30px;
            background-color: transparent;
        }

        /* 头像容器样式 */
        QWidget[objectName="avatarContainer"] {
            background-color: transparent;
            border: none;
        }

        /* 收起状态的头像容器 */
        QWidget[objectName="avatarContainer"][collapsed="true"] {
            background-color: transparent;
            border: none;
            margin: 0px;
            padding: 0px;
        }

        #usernameLabel {
            color: #FFFFFF; /* 使用纯白色，确保在深色背景下清晰可见 */
            font-size: 16px; /* 适中的字体大小 */
            font-weight: bold;
            margin-bottom: 2px;
            /* 移除不支持的text-shadow属性 */
            padding: 2px 0px; /* 增加垂直内边距 */
        }

        #statusLabel {
            color: #E8F4FD; /* 使用浅蓝白色，确保高对比度 */
            font-size: 12px; /* 适中的字体大小 */
            font-weight: 600; /* 增加字重 */
            /* 移除不支持的text-shadow属性 */
            padding: 1px 0px; /* 增加垂直内边距 */
        }

        #levelLabel {
            color: #FFD700; /* 使用更亮的金色，提高可见性 */
            font-size: 12px; /* 适中的字体大小 */
            font-weight: 600;
            /* 移除不支持的text-shadow属性 */
            padding: 1px 0px; /* 增加垂直内边距 */
        }

        /* 用户信息容器样式 */
        QWidget[objectName="userInfoWidget"] {
            background-color: transparent;
            border: none;
            margin: 0px;
            padding: 2px;
        }

        #sidebarGroup {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %3, stop:0.5 rgba(52, 73, 94, 0.8), stop:1 %3);
            border: 2px solid %2;
            border-radius: 20px; /* 更圆滑的边角 */
            margin: 3px 1px; /* 展开状态下减少左右边距 */
            padding: 1px; /* 减少内边距，让按钮有更多空间 */
            /* 移除不支持的box-shadow属性 */
        }

        /* 收起状态的容器样式 */
        #sidebarGroup[collapsed="true"] {
            margin: 3px 0px; /* 收起状态下恢复边距 */
            padding: 2px; /* 收起状态下的内边距 */
        }

        #sidebarGroup::title {
            color: %6;
            font-size: 14px;
            font-weight: bold;
            padding: 0 12px;
            /* 移除不支持的text-shadow属性 */
        }

        #menuButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %4, stop:0.5 rgba(52, 73, 94, 0.7), stop:1 %4);
            color: %7;
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 16px;
            padding: 10px 6px; /* 减少左右内边距，让按钮更宽 */
            text-align: center;
            font-size: 14px;
            font-weight: 500;
            min-width: 0px;
            max-width: none;
            /* 移除不支持的transition和box-shadow属性 */
        }

        /* 收起状态的按钮样式 */
        #menuButton[collapsed="true"] {
            padding: 8px 2px;
            font-size: 18px;
            font-weight: bold;
            min-width: 72px;
            max-width: 76px;
        }

        #menuButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %8, stop:0.5 rgba(74, 144, 226, 0.9), stop:1 %8);
            border-color: %6;
            color: white;
            transform: translateY(-3px) scale(1.02); /* 上浮 + 轻微放大 */
            box-shadow: 0 8px 25px rgba(74, 144, 226, 0.3); /* 更柔和的阴影 */
            border-radius: 18px; /* 悬停时稍微圆滑 */
            text-align: center;
        }

        #menuButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %9, stop:0.5 #2980B9, stop:1 %9);
            transform: translateY(-1px) scale(0.98); /* 轻微下压效果 */
            box-shadow: 0 2px 8px rgba(74, 144, 226, 0.4);
            text-align: center;
        }

        #menuButton[active="true"] {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %6, stop:0.5 #3498DB, stop:1 %7);
            color: white;
            border-color: %6;
            font-weight: 600;
            /* 移除不支持的box-shadow属性 */
            text-align: center;
            border-width: 3px; /* 激活状态边框更粗 */
        }

        #menuButton[menuType="primary"] {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(74, 144, 226, 0.4), stop:0.5 rgba(52, 152, 219, 0.5), stop:1 rgba(74, 144, 226, 0.4));
            border-color: %6;
            border-width: 2.5px; /* 主要按钮边框稍粗 */
            font-weight: 600;
            text-align: center;
            /* 移除不支持的box-shadow属性 */
        }



        #separator {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 transparent, stop:0.5 rgba(74, 144, 226, 0.4), stop:1 transparent);
            margin: 3px 8px; /* 适中的边距 */
            height: 2px;
            border-radius: 1px;
        }

        #menuSeparator {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 transparent, stop:0.5 rgba(74, 144, 226, 0.3), stop:1 transparent);
            margin: 4px 6px; /* 适中的边距 */
            height: 1px;
            border: none;
            border-radius: 0.5px;
        }

        #footerWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %4, stop:0.5 rgba(44, 62, 80, 0.8), stop:1 %4);
            border-top: 2px solid %2;
            border-radius: 20px 20px 0 0; /* 更圆滑的顶部边角 */
            margin: 4px 0px 0px 0px; /* 适应80px宽度 */
            padding: 3px; /* 适中的内边距 */
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1); /* 向上的阴影 */
        }

        /* 退出登录按钮 */
        #logoutButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(231, 76, 60, 0.9), stop:0.5 rgba(192, 57, 43, 0.9), stop:1 rgba(231, 76, 60, 0.9));
            color: white;
            border: 2px solid rgba(231, 76, 60, 0.7);
            border-radius: 18px;
            padding: 10px 8px;
            font-size: 13px;
            font-weight: 600;
            text-align: center;
            /* 移除不支持的transition和box-shadow属性 */
            min-width: 0px;
            max-width: none;
        }

        #logoutButton[collapsed="true"] {
            padding: 8px 2px;
            font-size: 18px;
            min-width: 72px;
            max-width: 76px;
        }

        /* 折叠按钮 */
        #collapseButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %8, stop:0.5 rgba(52, 152, 219, 0.9), stop:1 %8);
            color: white;
            border: 2px solid %6;
            border-radius: 18px;
            padding: 10px 8px;
            font-size: 13px;
            font-weight: 600;
            text-align: center;
            /* 移除不支持的transition和box-shadow属性 */
            min-width: 0px;
            max-width: none;
        }

        #collapseButton[collapsed="true"] {
            padding: 8px 2px;
            font-size: 18px;
            min-width: 72px;
            max-width: 76px;
        }

        #logoutButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(231, 76, 60, 1.0), stop:0.5 rgba(192, 57, 43, 1.0), stop:1 rgba(231, 76, 60, 1.0));
            border-color: rgba(231, 76, 60, 0.9);
            /* 移除不支持的box-shadow和transform属性 */
            border-radius: 20px;
            text-align: center;
        }

        #collapseButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(74, 144, 226, 1.0), stop:0.5 rgba(52, 152, 219, 1.0), stop:1 rgba(74, 144, 226, 1.0));
            border-color: rgba(74, 144, 226, 0.9);
            /* 移除不支持的box-shadow和transform属性 */
            border-radius: 20px;
            text-align: center;
        }
    )").arg(gradientColors, borderColor, groupBackground, buttonBackground, profileBackground, primaryAccent, secondaryAccent, hoverAccent, activeAccent, m_textColor));
}

void SidebarWidget::updateAvatarSize(int size)
{
    m_avatarLabel->setFixedSize(size, size);

    // 重新生成对应尺寸的头像
    QPixmap avatar(size, size);
    avatar.fill(Qt::transparent);
    QPainter painter(&avatar);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制渐变背景
    QRadialGradient gradient(size/2, size/2, size/2);
    gradient.setColorAt(0, QColor(m_primaryColor));
    gradient.setColorAt(1, QColor("#3498DB"));
    painter.setBrush(QBrush(gradient));
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(0, 0, size, size);

    // 绘制文字 - 根据尺寸调整字体大小
    painter.setPen(QColor("#FFFFFF"));
    int fontSize = size < 45 ? 14 : 18; // 调整字体大小阈值
    painter.setFont(QFont("Arial", fontSize, QFont::Bold));

    // 获取当前用户名的首字母 - 改进获取逻辑
    QString initial = "U";
    if (m_authService && m_authService->isAuthenticated()) {
        QString username = m_authService->getCurrentUser().username;
        if (!username.isEmpty()) {
            initial = username.left(1).toUpper();
        }
    } else {
        // 如果认证服务不可用，尝试从用户名标签获取
        if (m_usernameLabel && !m_usernameLabel->text().isEmpty()) {
            initial = m_usernameLabel->text().left(1).toUpper();
        }
    }
    painter.drawText(avatar.rect(), Qt::AlignCenter, initial);

    // 添加边框 - 根据尺寸调整边框
    if (size >= 50) {
        // 大头像使用较粗边框
        painter.setPen(QPen(QColor("#FFFFFF"), 2));
        painter.setBrush(Qt::NoBrush);
        painter.drawEllipse(1, 1, size-2, size-2);
    } else {
        // 小头像使用细边框，保持美观
        painter.setPen(QPen(QColor("#FFFFFF"), 1));
        painter.setBrush(Qt::NoBrush);
        painter.drawEllipse(1, 1, size-2, size-2);
    }

    m_avatarLabel->setPixmap(avatar);
}

void SidebarWidget::forceUpdateUserInfo()
{
    // 强制更新用户信息显示，确保在展开后信息正确显示
    if (m_authService && m_authService->isAuthenticated()) {
        AuthService::UserInfo userInfo = m_authService->getCurrentUser();

        // 确保布局设置正确
        m_userProfileLayout->setAlignment(Qt::AlignLeft);
        m_userProfileLayout->setContentsMargins(10, 10, 10, 10);  // 与CSS padding保持一致

        // 确保容器大小正确
        m_avatarContainer->setFixedSize(65, 65);
        m_userProfileWidget->setMinimumHeight(75); // 与CSS min-height保持一致

        // 首先确保容器可见
        m_userProfileWidget->setVisible(true);
        m_userProfileWidget->show();
        m_userInfoWidget->setVisible(true);
        m_userInfoWidget->show();

        // 确保标签可见并设置内容
        m_usernameLabel->setVisible(true);
        m_usernameLabel->setText(userInfo.username);

        m_statusLabel->setVisible(true);
        m_statusLabel->setText("🟢 在线");

        m_levelLabel->setVisible(true);
        int level = userInfo.loginCount / 10 + 1;
        m_levelLabel->setText(QString("⭐ Lv.%1").arg(level));

        // 更新头像
        updateAvatarSize(65);

        // 强制重新布局和重绘
        m_userInfoWidget->updateGeometry();
        m_userProfileWidget->updateGeometry();

        // 强制重新应用样式
        m_userProfileWidget->style()->unpolish(m_userProfileWidget);
        m_userProfileWidget->style()->polish(m_userProfileWidget);

        m_usernameLabel->repaint();
        m_statusLabel->repaint();
        m_levelLabel->repaint();

        // 强制布局更新
        m_userInfoWidget->updateGeometry();
        m_userProfileWidget->updateGeometry();

        // 强制重新应用样式
        m_userInfoWidget->style()->unpolish(m_userInfoWidget);
        m_userInfoWidget->style()->polish(m_userInfoWidget);

        qDebug() << "强制更新用户信息完成:" << userInfo.username;
    }
}

void SidebarWidget::initializeButtonProperties()
{
    // 为所有按钮设置初始属性
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    for (QPushButton *btn : buttons) {
        // 设置初始折叠状态
        btn->setProperty("collapsed", m_collapsed);

        // 保存按钮的完整文本
        if (btn->property("fullText").toString().isEmpty()) {
            btn->setProperty("fullText", btn->text());
        }

        // 强制应用样式
        btn->style()->unpolish(btn);
        btn->style()->polish(btn);
    }

    // 为容器设置初始属性
    if (m_navigationGroup) {
        m_navigationGroup->setProperty("collapsed", m_collapsed);
        m_navigationGroup->style()->unpolish(m_navigationGroup);
        m_navigationGroup->style()->polish(m_navigationGroup);
    }
}

/**
 * @brief 设置退出按钮模式
 * @param isInGame 是否在游戏中
 *
 * 动态更改退出按钮的文本和功能
 */
void SidebarWidget::setExitButtonMode(bool isInGame)
{
    m_isInGame = isInGame;

    if (!m_logoutButton) {
        return;
    }

    // 断开之前的连接
    disconnect(m_logoutButton, &QPushButton::clicked, this, &SidebarWidget::logoutClicked);
    disconnect(m_logoutButton, &QPushButton::clicked, this, &SidebarWidget::exitGameClicked);

    if (isInGame) {
        // 游戏模式：显示"退出游戏"
        m_logoutButton->setText("🎮 退出游戏");
        m_logoutButton->setToolTip("退出当前游戏，返回游戏服务器选择界面");
        m_logoutButton->setProperty("fullText", "🎮 退出游戏");

        // 连接到退出游戏信号
        connect(m_logoutButton, &QPushButton::clicked, this, &SidebarWidget::exitGameClicked);

        qDebug() << "SidebarWidget: 切换到游戏模式 - 退出游戏按钮";
    } else {
        // 正常模式：显示"安全退出"
        m_logoutButton->setText("🚪 安全退出");
        m_logoutButton->setToolTip("退出登录并关闭应用");
        m_logoutButton->setProperty("fullText", "🚪 安全退出");

        // 连接到登出信号
        connect(m_logoutButton, &QPushButton::clicked, this, &SidebarWidget::logoutClicked);

        qDebug() << "SidebarWidget: 切换到正常模式 - 安全退出按钮";
    }

    // 如果当前是收缩状态，更新按钮显示
    if (m_collapsed) {
        updateCollapseState();
    }
}
